package com.xyd.Servlet;

import com.xyd.Service.AdminService;
import com.xyd.Service.UserService;
import com.xyd.bean.Admin;
import com.xyd.bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/UserAndAdminLoginServlet")
public class UserAndAdminLoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserService userService=new UserService();
        AdminService adminService=new AdminService();
        //登录
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        //输入的验证码
        String veryCode = request.getParameter("veryCode");
        //服务器生成的验证码
        String captchaVeryCode = (String) request.getSession().getAttribute("captcha");
        int choose = Integer.parseInt(request.getParameter("choose"));
        if (veryCode.equalsIgnoreCase(captchaVeryCode)){
            if (choose==0){
                Admin admin = adminService.loginAdmin(name,password);
                if (admin!=null){
                    request.getSession().setAttribute("admin",admin);
                    request.getRequestDispatcher("/manage/index.html").forward(request,response);
                }

            }else {
                User user = userService.loginUser(name,password);
                if (user!=null){
                    request.getSession().setAttribute("uname",name);
                    request.getSession().setAttribute("user",user);
                    request.getRequestDispatcher("/index.jsp").forward(request,response);
                }
            }
        }else {
            response.getWriter().print("<h2>登录失败,请重新输入</h2>");
            response.sendRedirect("/login.html");
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
